<template>
  <div class="ip-visits-container">
    <el-card title="IP访问查询" class="chart-card">
      <el-space direction="vertical" style="width: 100%">
        <el-space>
          <el-input
            v-model="searchIp"
            placeholder="输入IP地址"
            @keyup.enter="handleSearch"
            style="width: 200px"
          />
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
            :loading="loading"
          >
            查询
          </el-button>
        </el-space>

        <IpVisitsTable
          v-if="ipVisits"
          :ip-visits="ipVisits.visits"
          :loading="loading"
          @view-session="handleViewSession"
        />
      </el-space>
    </el-card>

    <!-- IP列表 -->
    <el-card title="网站访问IP列表" class="chart-card" style="margin-top: 24px">
      <el-button @click="fetchIpList" :loading="ipListLoading" style="margin-bottom: 12px">
        刷新IP列表
      </el-button>
      
      <!-- IP访问统计图表 -->
      <el-tabs v-model="activeChartTab" type="card" v-if="ipList.length > 0" style="margin-bottom: 16px">
        <el-tab-pane label="访问次数分布" name="visits">
          <div ref="visitsChartRef" style="width: 100%; height: 300px"></div>
        </el-tab-pane>
        <el-tab-pane label="设备分布" name="device">
          <div ref="deviceChartRef" style="width: 100%; height: 300px"></div>
        </el-tab-pane>
        <el-tab-pane label="浏览器分布" name="browser">
          <div ref="browserChartRef" style="width: 100%; height: 300px"></div>
        </el-tab-pane>
        <el-tab-pane label="操作系统分布" name="os">
          <div ref="osChartRef" style="width: 100%; height: 300px"></div>
        </el-tab-pane>
      </el-tabs>
      
      <el-table
        :data="ipList"
        :loading="ipListLoading"
        row-key="ip"
        style="width: 100%"
      >
        <el-table-column prop="ip" label="IP地址">
          <template #default="{ row }">
            <el-text strong>{{ row.ip }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="totalVisits" label="访问次数" sortable />
        <el-table-column prop="lastVisit" label="最近访问" sortable>
          <template #default="{ row }">
            {{ row.lastVisit ? new Date(row.lastVisit).toLocaleString() : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="device" label="设备" />
        <el-table-column prop="browser" label="浏览器" />
        <el-table-column prop="os" label="操作系统" />
        <el-table-column prop="country" label="国家">
          <template #default="{ row }">
            {{ row.country || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="city" label="城市">
          <template #default="{ row }">
            {{ row.city || '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 会话详情模态框 -->
    <el-dialog
      v-model="sessionModalVisible"
      title="会话详情"
      width="800px"
    >
      <SessionDetails
        :session-data="sessionData"
        :loading="sessionLoading"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useTrackingStore } from '@/store/tracking'
import trackingAPI from '@/api/tracking.api'
import IpVisitsTable from './charts/IpVisitsTable.vue'
import SessionDetails from './charts/SessionDetails.vue'
import * as echarts from 'echarts'

const trackingStore = useTrackingStore()
// 使用 storeToRefs 保持响应式
const { currentWebsite } = storeToRefs(trackingStore)

const searchIp = ref('')
const ipVisits = ref<any>(null)
const loading = ref(false)
const sessionModalVisible = ref(false)
const sessionData = ref<any>(null)
const sessionLoading = ref(false)
const ipList = ref<any[]>([])
const ipListLoading = ref(false)
const activeChartTab = ref('visits')

// 图表引用
const visitsChartRef = ref<HTMLElement>()
const deviceChartRef = ref<HTMLElement>()
const browserChartRef = ref<HTMLElement>()
const osChartRef = ref<HTMLElement>()

// 图表实例
let visitsChart: echarts.ECharts | null = null
let deviceChart: echarts.ECharts | null = null
let browserChart: echarts.ECharts | null = null
let osChart: echarts.ECharts | null = null

// 处理访问次数分布数据
const visitsChartData = computed(() => {
  if (!ipList.value || ipList.value.length === 0) return { ips: [], visits: [] }
  
  // 按访问次数排序，取前10个
  const sorted = [...ipList.value].sort((a, b) => {
    const aVisits = Number(a.totalVisits) || 0
    const bVisits = Number(b.totalVisits) || 0
    return bVisits - aVisits
  }).slice(0, 10)
  
  return {
    ips: sorted.map(item => item.ip),
    visits: sorted.map(item => Number(item.totalVisits) || 0)
  }
})

// 处理设备分布数据
const deviceChartData = computed(() => {
  if (!ipList.value || ipList.value.length === 0) return []
  
  const deviceMap: Record<string, number> = {}
  ipList.value.forEach(item => {
    const device = item.device || '未知'
    deviceMap[device] = (deviceMap[device] || 0) + (Number(item.totalVisits) || 0)
  })
  
  return Object.entries(deviceMap).map(([name, value]) => ({ name, value }))
})

// 处理浏览器分布数据
const browserChartData = computed(() => {
  if (!ipList.value || ipList.value.length === 0) return []
  
  const browserMap: Record<string, number> = {}
  ipList.value.forEach(item => {
    const browser = item.browser || '未知'
    browserMap[browser] = (browserMap[browser] || 0) + (Number(item.totalVisits) || 0)
  })
  
  return Object.entries(browserMap).map(([name, value]) => ({ name, value }))
})

// 处理操作系统分布数据
const osChartData = computed(() => {
  if (!ipList.value || ipList.value.length === 0) return []
  
  const osMap: Record<string, number> = {}
  ipList.value.forEach(item => {
    const os = item.os || '未知'
    osMap[os] = (osMap[os] || 0) + (Number(item.totalVisits) || 0)
  })
  
  return Object.entries(osMap).map(([name, value]) => ({ name, value }))
})

// 初始化访问次数分布图表
const initVisitsChart = () => {
  if (!visitsChartRef.value || visitsChartData.value.ips.length === 0) return
  
  if (visitsChart) {
    visitsChart.dispose()
  }
  
  visitsChart = echarts.init(visitsChartRef.value)
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: visitsChartData.value.ips,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '访问次数'
    },
    series: [{
      name: '访问次数',
      type: 'bar',
      data: visitsChartData.value.visits,
      itemStyle: {
        color: '#409EFF'
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  }
  
  visitsChart.setOption(option)
}

// 初始化设备分布图表
const initDeviceChart = () => {
  if (!deviceChartRef.value || deviceChartData.value.length === 0) return
  
  if (deviceChart) {
    deviceChart.dispose()
  }
  
  deviceChart = echarts.init(deviceChartRef.value)
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: deviceChartData.value.map(item => item.name)
    },
    series: [{
      name: '设备分布',
      type: 'pie',
      radius: ['40%', '70%'],
      data: deviceChartData.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  deviceChart.setOption(option)
}

// 初始化浏览器分布图表
const initBrowserChart = () => {
  if (!browserChartRef.value || browserChartData.value.length === 0) return
  
  if (browserChart) {
    browserChart.dispose()
  }
  
  browserChart = echarts.init(browserChartRef.value)
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: browserChartData.value.map(item => item.name)
    },
    series: [{
      name: '浏览器分布',
      type: 'pie',
      radius: ['40%', '70%'],
      data: browserChartData.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  browserChart.setOption(option)
}

// 初始化操作系统分布图表
const initOsChart = () => {
  if (!osChartRef.value || osChartData.value.length === 0) return
  
  if (osChart) {
    osChart.dispose()
  }
  
  osChart = echarts.init(osChartRef.value)
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: osChartData.value.map(item => item.name)
    },
    series: [{
      name: '操作系统分布',
      type: 'pie',
      radius: ['40%', '70%'],
      data: osChartData.value,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  osChart.setOption(option)
}

// 初始化所有图表
const initAllCharts = () => {
  nextTick(() => {
    if (activeChartTab.value === 'visits') {
      initVisitsChart()
    } else if (activeChartTab.value === 'device') {
      initDeviceChart()
    } else if (activeChartTab.value === 'browser') {
      initBrowserChart()
    } else if (activeChartTab.value === 'os') {
      initOsChart()
    }
  })
}

// 窗口大小改变时调整图表
const handleResize = () => {
  visitsChart?.resize()
  deviceChart?.resize()
  browserChart?.resize()
  osChart?.resize()
}

const handleSearch = async () => {
  if (!searchIp.value) {
    ElMessage.warning('请输入IP地址')
    return
  }
  
  loading.value = true
  try {
    const response = await trackingAPI.getIpVisits(
      searchIp.value,
      currentWebsite.value ? { websiteId: currentWebsite.value._id } : {}
    )
    // 处理不同的响应格式
    ipVisits.value = response?.data || response || null
  } catch (error: any) {
    console.error('获取IP访问记录失败:', error)
    ElMessage.error('获取IP访问记录失败')
  } finally {
    loading.value = false
  }
}

const fetchIpList = async () => {
  if (!currentWebsite.value) return
  
  ipListLoading.value = true
  try {
    const response = await trackingAPI.getWebsiteIps(currentWebsite.value._id)
    // 处理不同的响应格式
    let ipListData: any[] = []
    if (Array.isArray(response)) {
      ipListData = response
    } else if (response?.data && Array.isArray(response.data)) {
      ipListData = response.data
    }
    ipList.value = ipListData
  } catch (error: any) {
    console.error('获取IP列表失败:', error)
    ElMessage.error('获取IP列表失败')
  } finally {
    ipListLoading.value = false
  }
}

const handleViewSession = async (sessionId: string) => {
  sessionLoading.value = true
  sessionModalVisible.value = true
  try {
    const response = await trackingAPI.getSessionDetails(sessionId)
    // 处理不同的响应格式
    sessionData.value = response?.data || response || null
  } catch (error: any) {
    console.error('获取会话详情失败:', error)
    ElMessage.error('获取会话详情失败')
  } finally {
    sessionLoading.value = false
  }
}

// 监听 IP 列表变化，更新图表
watch(ipList, () => {
  initAllCharts()
}, { deep: true })

// 监听图表标签页切换
watch(activeChartTab, () => {
  initAllCharts()
})

watch(currentWebsite, () => {
  if (currentWebsite.value) {
    fetchIpList()
  }
}, { immediate: true })

onMounted(() => {
  window.addEventListener('resize', handleResize)
  initAllCharts()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  visitsChart?.dispose()
  deviceChart?.dispose()
  browserChart?.dispose()
  osChart?.dispose()
})
</script>

<style scoped lang="scss">
.ip-visits-container {
  .chart-card {
    border-radius: 8px;
    margin-bottom: 24px;
  }
}
</style>

